import {reactive} from "vue"

/**
 * 滚动条钩子函数参选
 */
type ScrollbarHookParams = {
    PullupLoading?: () => void //上拉加载回调函数
    DropdownLoading?: () => void//下拉加载回调函数
}

/**
 * 滚动条滚动事件hook
 * @param params
 */
export function useScrollbarHook(params?: ScrollbarHookParams) {
    /**
     * 页面加载判断
     */
    const loading = reactive({
        top: 0,
        status: false,
        type: 'dropdown'
    })

    /**
     * 滚动条滚动触发事件
     * @param event
     * @constructor
     */
    function OnScrollChange(event: any) {
        const num: number = Math.abs(event.scrollTop - loading.top)
        if (event.scrollTop > loading.top) {//下拉
            if (num < 100 && !loading.status) {
                loading.status = true
                if (params && typeof params.DropdownLoading === 'function') {
                    params.DropdownLoading()
                }
            }
            if (loading.type !== 'dropdown') {
                loading.status = false
            }
            loading.type = 'dropdown'
        } else {//上拉
            if (num < 100 && !loading.status) {
                if (params && typeof params.PullupLoading === 'function') {
                    params.PullupLoading()
                }
                loading.status = true
            }
            if (loading.type !== 'pullup') {
                loading.status = false
            }
            loading.type = 'pullup'
        }
        //记忆位置
        loading.top = event.scrollTop
    }


    /**
     * 导出滚动条滚动事件
     */
    return {OnScrollChange}
}